<?php
namespace app\appapi\controller;
use think\Controller;
use think\Request;
use think\Db;
use app\appapi\WeShare;

class WeRegisterland extends Common

{

    //获取小程序二维码
    function getWecode($path='wxcode/'){
        $data = input('post.');
        if(empty($data['path']) || !$data['path'] || empty($data['uid']) || !$data['uid'])
        return json_encode(['code'=>10002,'msg'=>'Parameter error']);
        $path = $data['path'];
        $uid = $data['uid'];
        $width = 430;
        $file = $path.substr($uid,2,5).'.png';
        if (!file_exists($file))
        {
            $access_token = $this->getWxAppToken();
            // $post_data='{"sence":"'.$uid.'","page":"'.$path.'","width":'.$width.'}';
            // $post_data = json_encode($post_data);
            // $url="https://api.weixin.qq.com/wxa/getwxacodeunlimit?access_token=".$access_token;
            $post_data='{"path":"'.$path.'","width":'.$width.'}';
            $url="https://api.weixin.qq.com/cgi-bin/wxaapp/createwxaqrcode?access_token=".$access_token;
            $weapp = new WeShare();
            $result = $weapp->postDataCurl($url,$post_data);
            if(!is_dir($path)){
                mkdir(iconv("UTF-8", "GBK", $path), 0777, true);
            }
            if(!file_put_contents($paths, base64_decode($result), false))
            return json_encode(['code'=>10002,'msg'=>'Network anomaly']);
        }
        $arr = dirname($_SERVER['SCRIPT_NAME']).'/'.$file.substr($uid,2,5).'.png';
        return json_encode(['code'=>10001,'msg'=>'ok','data'=>$arr]);
    }

    //获取用户OPENID
    function getUserId(){
        $data = input('get.');
        if(empty($data['code']) || !$data['code'])
        return json_encode(['code'=>10002,'msg'=>'Parameter error']);
        $code = $data['code'];
        $wAppconfig = getWxconfig('weAppSystem');
        $apid = $wAppconfig['app_id'];
        $serect = $wAppconfig['secret'];
        $url='https://api.weixin.qq.com/sns/jscode2session?appid='.$apid.'&secret='.$serect.'&js_code='.$code.'&grant_type=authorization_code';
        $weapp = new WeShare(); 
        if(!$result = $weapp->getDataCurl($url))
        return json_encode(['code'=>10002,'msg'=>'Network anomaly']);
        if(!empty($result['errcode']))
        return json_encode(['code'=>10002,'msg'=>'privilege grant failed','info'=>$result]);
        $arr['openid'] = $result['openid'];
        $arr = [
            'oid'=>$result['openid'],
            'uid'=>md5($result['openid']),
        ];
        if($this->_addUserInfo($arr)){
            cache('we_user_id',$arr['uid'],60*10);//缓存有效期10分钟
            unset($arr['oid']);
            $arr['ss_key'] = $result['session_key'];
            $arr['cc_token'] = $this->getWxAppToken($apid,$serect,$weapp);
            // $arr['State'] = getUserInfo($arr['uid'],'State');
            return json_encode(['code'=>10001,'msg'=>'ok','data'=>$arr]);
        }
        return json_encode(['code'=>10002,'msg'=>'Network anomaly']);
        
    }


    //新增用户数据
    private function _addUserInfo($data)
    {
        if(empty($data['uid']) || !$data['uid'] || empty($data['oid']) || !$data['oid'])
        return false;
        $arr = [
            'User_id'=>$data['uid'],
            'Openid'=>$data['oid'],
        ];
        $db = Db::name('user');
        $time = time();
        if($re = $db->where($arr)->find()){
            $info['Land_time'] = $time;
            if(judgeDiffDays(getdate($re['Add_friends_time']),getdate(time()))){
                $info['Add_friends_second'] = 0;
            }
            if(judgeDiffDays(getdate($re['Cash_time']),getdate(time()))){
                $info['Cash_time'] = 0;
                $info['Cash_amount'] = 0;
            }
            if($db->where($arr)->update($info))
            return true;
        }else{
            $arr['Land_time'] = $time;
            $arr['Addtime'] = $time;
            if($db->insert($arr))
            return true;
        }
        return false;
    }

    //更新用户数据
    public function updateUserInfo(){
        $data = input('post.');
        if($arr = $this->_updateUserInfo($data))
        return json_encode(['code'=>10001,'msg'=>'Update success','data'=>$data]);
        return json_encode(['code'=>10002,'msg'=>'Network anomaly']);
    } 

    private function _updateUserInfo($data)
    {
        if(empty($data['uid']) || !$data['uid'])
        return false;
        $arr = [
            'User_id' =>$data['uid'],
            'Username'=>$data['nickName'],
            'Password'=>md5($data['nickName']),
            'Head_portrait'=>$data['avatarUrl'],
        ];
        $where['User_id'] = ['=',$data['uid']];
        $db = Db::name('user');
        if($db->where($arr)->find())
        return true;
        unset($arr['User_id']);
        if($db->where($where)->update($arr))         
        return true;
        return false;
  }
}
